package com.huaxin.hxcloud.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.WorkFlowDTO;
import com.huaxin.common.Entity.WorkFlowTaskDetail;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.utils.SpacesItemDecoration;
import com.huaxin.hxcloud.R;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author lwjing
 * @date 2018/3/23
 * @Desc $desc$ 任务单下发---》人员分配审核-----》归档考核
 * Copyright HUAXIN DATA. All rights reserved.
 */
public class HxTaskWaitDoActivity extends BaseActivity {
    @BindView(R.id.toolbar)
    Toolbar            toolbar;
    @BindView(R.id.rl_task_waitdo)
    RecyclerView       rl_task_waitdo;
    @BindView(R.id.refresh)
    SwipeRefreshLayout mSwipeRefreshLayout;

    private View              emptyView;
    private TaskWaitdoAdapter flowTaskAdapter;
    List<WorkFlowDTO.WorkFlowTask> workflowTaskArr = new ArrayList<>();

    //api请求页数
    private int page     = 0;
    //单页最大条目数
    private int pageSize = 30;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_task_waitdo;
    }

    @Override
    protected int getLoadFrameId() {
        return R.id.content;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
    }

    @Override
    public void initView() {
        setSupportActionBar(toolbar);
        toolbar.setTitle("待办任务");
        rl_task_waitdo.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL,
                false));
        flowTaskAdapter = new TaskWaitdoAdapter(R.layout.item_workflow_waitdo, workflowTaskArr);
        flowTaskAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                //加载更多
                mSwipeRefreshLayout.setRefreshing(false);
                apiWorkFlowTask(true);
            }
        });
        rl_task_waitdo.setAdapter(flowTaskAdapter);
        //设置条目间距
        rl_task_waitdo.addItemDecoration(new SpacesItemDecoration(30));
        //空布局
        emptyView = LayoutInflater.from(this).inflate(R.layout.item_empty_nodata_center, (ViewGroup) rl_task_waitdo.getParent(), false);

        flowTaskAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                itemClick(position);
            }
        });

        flowTaskAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                itemChildClick(view, i);
            }
        });
        flowTaskAdapter.setEnableLoadMore(false);
        mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(47, 223, 189));
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 0;
                workflowTaskArr.clear();
                flowTaskAdapter.setEnableLoadMore(false);
                apiWorkFlowTask(false);
            }
        });
        //  mSwipeRefreshLayout.setRefreshing(true);

    }

    private void itemChildClick(View view, int position) {
        //0 巡检审批 1巡检计划审批 2维修保养审批 3分发 4 考核 5无视（之后会剔除）  （节点状态）
        //0 巡检工单 1 维修保养单 2巡检计划  （工单类型）
        switch (view.getId()) {
            case R.id.tv_state:
                //节点状态
                itemClick(position);
                break;
            case R.id.tv_type:
                //工单类型
                taskTypeItemClick(position);
                break;
        }


    }

    private void taskTypeItemClick(int position) {
        WorkFlowDTO.WorkFlowTask workFlowTask = workflowTaskArr.get(position);
        int type = workFlowTask.getTask().getType();
        Intent intent = new Intent();
        if (type == 0) {
            intent.setClass(this, HxXunJianCheckActivity.class);
            intent.putExtra(Constants.IK_ARRANGE_ID, workflowTaskArr.get(position).getTask().getId());
            intent.putExtra(Constants.IK_TASK_ID, workflowTaskArr.get(position).getId());
            //审核归档 和 巡检计划区分
            intent.putExtra(Constants.IK_TASK_TYPE, workFlowTask.getType());
            startActivity(intent);
        } else if (type == 1) {
            intent.setClass(this, HxRepairUpCheckActivity.class);
            intent.putExtra(Constants.IK_CUNJIAN_ID, workflowTaskArr.get(position).getTask().getId());
            intent.putExtra(Constants.IK_TASK_ID, workflowTaskArr.get(position).getId());
            //审核归档
            intent.putExtra(Constants.IK_TASK_TYPE, workFlowTask.getType());
            startActivity(intent);

        } else if (type == 2) {
            intent.setClass(this, HxXunJianPlanActivity.class);
            intent.putExtra(Constants.IK_CUNJIAN_ID, workflowTaskArr.get(position).getTask().getId());
            intent.putExtra(Constants.IK_TASK_ID, workflowTaskArr.get(position).getId());
            startActivity(intent);
        }
    }

    /**
     * 条目点击
     *
     * @param position
     */
    private void itemClick(int position) {
        //根据不同type跳转不同界面
        WorkFlowDTO.WorkFlowTask workFlowTask = workflowTaskArr.get(position);
        //0 巡检审批 1巡检计划审批 2维修保养审批 3分发 4 考核归档
        Intent intent = new Intent();
        int type = workFlowTask.getType();
        switch (type) {
            //在人员分发接口中直接做任务单审核
            case 0:
                //                intent.setClass(this, HxXunJianCheckActivity.class);
                //                intent.putExtra(Constants.IK_ARRANGE_ID, workflowTaskArr.get(position).getTask().getId());
                //                intent.putExtra(Constants.IK_TASK_ID, workflowTaskArr.get(position).getId());
                //                startActivity(intent);
            case 2:
            case 3:
                intent.setClass(this, HxWorkFlowHandoutActivity.class);
                intent.putExtra(Constants.IK_ARRANGE_ID, workflowTaskArr.get(position).getTask().getId());
                intent.putExtra(Constants.IK_TASK_ID, workflowTaskArr.get(position).getId());
                startActivity(intent);
                break;
            case 1:
                intent.setClass(this, HxXunJianPlanActivity.class);
                intent.putExtra(Constants.IK_CUNJIAN_ID, workflowTaskArr.get(position).getTask().getId());
                intent.putExtra(Constants.IK_TASK_ID, workflowTaskArr.get(position).getId());
                startActivity(intent);
                break;
            //            case 2:
            //            intent.setClass(this, HxRepairUpCheckActivity.class);
            //            intent.putExtra(Constants.IK_CUNJIAN_ID, workflowTaskArr.get(position).getTask().getId());
            //            intent.putExtra(Constants.IK_TASK_ID, workflowTaskArr.get(position).getId());
            //            startActivity(intent);
            //            case 3:
            //                intent.setClass(this, HxWorkFlowHandoutActivity.class);
            //                intent.putExtra(Constants.IK_ARRANGE_ID, workflowTaskArr.get(position).getTask().getId());
            //                intent.putExtra(Constants.IK_TASK_ID, workflowTaskArr.get(position).getId());
            //                startActivity(intent);
            //                break;
            case 4:
                //考核归档 按工单类型跳转界面改成分发人员
                taskTypeItemClick(position);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        page = 0;
        apiWorkFlowTask(false);
    }

    @Override
    protected void requestData() {
        super.requestData();
        //  apiWorkFlowTask(false);
    }

    private void apiWorkFlowTask(final boolean isLoadMore) {
        if (!isLoadMore) {
            updateLoadStatus(LOADING);
        }
        Call<WorkFlowDTO> call = HxTransmitRequestHelper.getRequestApi().getWorkFlowTaskList(page, pageSize);
        autoClose(call);
        Log.d(TAG, "ApiRequestData: " + call.request().url());
        call.enqueue(new Callback<WorkFlowDTO>() {
            @Override
            public void onResponse(Call<WorkFlowDTO> call, Response<WorkFlowDTO> response) {
                WorkFlowDTO workFlowDTO = response.body();
                if (response.isSuccessful() && workFlowDTO != null) {
                    updateLoadStatus(LOAD_SUCCESS);
                    WorkFlowDTO.WorkFlowBase workFlowBase = workFlowDTO.getData();
                    if (workFlowBase == null && page == 0) {
                        //空布局
                        flowTaskAdapter.setEmptyView(emptyView);
                    } else {

                        List<WorkFlowDTO.WorkFlowTask> workflowTaskArrPage = workFlowBase.getWorkflowTaskArr();
                        if (page == 0) {
                            workflowTaskArr.clear();
                            flowTaskAdapter.setNewData(workflowTaskArr);
                        }
                        if (workflowTaskArrPage != null && workflowTaskArrPage.size() > 0) {
                            workflowTaskArr.addAll(workflowTaskArrPage);
                            flowTaskAdapter.setNewData(workflowTaskArr);

                        } else if (page == 0) {
                            flowTaskAdapter.setEmptyView(emptyView);
                        }
                        page++;
                        if (isLoadMore) {
                            if (workflowTaskArrPage == null || workflowTaskArrPage.size() < pageSize) {
                                //第一页如果不够一页就不显示没有更多数据布局
                                flowTaskAdapter.loadMoreEnd(true);
                            } else {
                                flowTaskAdapter.loadMoreComplete();
                            }
                        }
                    }

                } else {
                    if (isLoadMore) {
                        flowTaskAdapter.loadMoreFail();
                    } else {
                        updateLoadStatus(LOAD_ERROR);
                    }
                }

                if (mSwipeRefreshLayout != null) {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
                flowTaskAdapter.setEnableLoadMore(true);
            }

            @Override
            public void onFailure(Call<WorkFlowDTO> call, Throwable t) {
                Log.d(TAG, "onFailure: ---->" + t);
                flowTaskAdapter.setEnableLoadMore(true);
                if (mSwipeRefreshLayout != null) {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
                if (isLoadMore) {
                    flowTaskAdapter.loadMoreFail();
                } else {
                    updateLoadStatus(LOAD_FAILURE);
                }
            }
        });
    }

    class TaskWaitdoAdapter extends BaseQuickAdapter<WorkFlowDTO.WorkFlowTask, BaseViewHolder> {

        public TaskWaitdoAdapter(int layoutResId, @Nullable List<WorkFlowDTO.WorkFlowTask> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder baseViewHolder, WorkFlowDTO.WorkFlowTask workFlowTask) {
            TextView tv_name = baseViewHolder.getView(R.id.tv_worktask_name);
            TextView tv_who_report = baseViewHolder.getView(R.id.tv_who_report);
            TextView tv_task_code = baseViewHolder.getView(R.id.tv_task_code);
            TextView tv_time = baseViewHolder.getView(R.id.tv_time);
            TextView tv_state = baseViewHolder.getView(R.id.tv_state);
            TextView tv_task_des = baseViewHolder.getView(R.id.tv_task_des);
            TextView tv_type = baseViewHolder.getView(R.id.tv_type);
            WorkFlowTaskDetail arrangeTask = workFlowTask.getTask();
            if (arrangeTask == null) {
                return;
            }
            //  tv_name.setText(arrangeTask.getTitle());
            loadTextColon(tv_name, "标题", arrangeTask.getTitle());
            loadTextColon(tv_who_report, "发起人", arrangeTask.getProposer());
            loadTextColon(tv_task_code, "编号", arrangeTask.getCode());
            loadTextColon(tv_task_des, "描述", workFlowTask.getDes());
            if (arrangeTask.getProposeTime() != 0) {
                loadTextColon(tv_time, "时间", dateFormat(arrangeTask.getProposeTime()));
            }
            loadTextColon(tv_state, "节点状态", getStateText(workFlowTask.getType(), arrangeTask.getType()));
            loadTextColon(tv_type, "工单类型", getTypeText(arrangeTask.getType()));
            baseViewHolder.addOnClickListener(R.id.tv_state);
            baseViewHolder.addOnClickListener(R.id.tv_type);
        }
    }

    private String getTypeText(int type) {
        switch (type) {
            case 0:
                return "巡检工单";
            case 1:
                return "维修保养";
            case 2:
                return "巡检计划";
            default:
                return "";
        }
    }

    private String getStateText(int type, int type2) {
        switch (type) {
            case 0:
            case 1:
            case 2:
                if (type2 == 2) {
                    return "领导审核";
                } else {
                    return "分配人员";
                }
            case 3:
                return "分配人员";
            case 4:
                return "归档考核";
            default:
                return "其他";
        }
    }
}
